package cn.message.service.impl;

import cn.itcast.mapper.*;
import cn.itcast.pojo.*;
import cn.itcast.util.CollectionUtil;
import cn.itcast.util.DoubleUtils;
import cn.itcast.util.HttpClientUtil;
import cn.message.service.IWithdrawService;
import cn.web.web_module.entity.WithdrawRechargeInfo;
import cn.web.web_module.mapper.WithdrawRechargeInfoMapper;
import cn.wx.MyConfig;
import cn.wx.WXPay;
import cn.wx.WXPayUtil;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 郭智超
 * @create 2020-04-03 15:44
 */
@Slf4j
@Service
public class WithdrawServiceImpl implements IWithdrawService {

    @Resource
    private withdrawMapper withdrawMapper;

    @Resource
    private orderMapper orderMapper;

    @Resource
    cn.itcast.mapper.accountMapper accountMapper;

    @Resource
    cn.itcast.mapper.infoMapper infoMapper;

    @Resource
    private WithdrawRechargeInfoMapper withdrawRechargeInfoMapper;

    @Resource
    private horsemanMapper horsemanMapper;


    @Override
    public Map<String, Object> getAllWithdraw(Map<String,String> map) {
        withdrawExample we = new withdrawExample();
        we.setOrderByClause("apply_time DESC");
        withdrawExample.Criteria criteria = we.createCriteria();

        //添加查询条件
        //根据用户姓名模糊搜索
        if(!map.get("name").isEmpty()) {
            criteria.andNameLike("%"+map.get("name")+"%");
        }
        //根据提现状态搜索
        if(!map.get("state").isEmpty()) {
            criteria.andStateEqualTo(map.get("state"));
        }
        String[] dateRanges = {};
        Date startDate = null;
        Date endDate = null;
        if (!map.get("dateRange").isEmpty()) {
            dateRanges = map.get("dateRange").split(",");
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                startDate = sdf.parse(dateRanges[0]);
                endDate = sdf.parse(dateRanges[1]);
                criteria.andApplyTimeBetween(startDate,endDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        //返回符合查询条件的总记录数
        int count = withdrawMapper.countByExample(we);

        int page = Integer.parseInt(map.get("page"));
        int limit = Integer.parseInt(map.get("limit"));
        //分页
        PageHelper.startPage(page,limit);
        //查询所有符合条件的商品分类的信息
        List<withdraw> withdrawList = withdrawMapper.selectByExample(we);

        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        //格式化申请时间、到账时间、转账时间
        for (withdraw withdraw2 : withdrawList) {
            if(withdraw2.getApplyTime() != null){
                withdraw2.setApplyTime_string(sdf.format(withdraw2.getApplyTime()));
            }
            if(withdraw2.getBillTime() != null){
                withdraw2.setBillTime_string(sdf.format(withdraw2.getBillTime()));
            }
            if(withdraw2.getTransfer() != null){
                withdraw2.setTransfer_string(sdf.format(withdraw2.getTransfer()));
            }
        }

        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("count",count);
        resultMap.put("withdrawList",withdrawList);

        return resultMap;
    }

    @Override
    public Map<String, Object> getOrderById(Integer page, Integer limit, String openId, order order) {
        orderExample orderExample = new orderExample();
        cn.itcast.pojo.orderExample.Criteria criteria = orderExample.createCriteria();

        //添加查询条件
        //根据订单状态进行搜索
        if(!order.getOrderState().isEmpty()) {
            criteria.andOrderStateEqualTo(order.getOrderState());
        }

        criteria.andOpenIdEqualTo(openId);


        //返回符合查询条件的总记录数
        int count = orderMapper.countByExample(orderExample);

        //分页
        PageHelper.startPage(page,limit);
        //查询所有符合搜索条件的订单
        List<order> orderList = orderMapper.selectByExample(orderExample);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("count",count);
        map.put("orderList",orderList);

        return map;
    }
    @Override
    public Boolean checkWithdraw(Integer id) {


        withdraw withdraw = withdrawMapper.selectByPrimaryKey(id);
        accountExample aEx = new accountExample();
        accountExample.Criteria criteria = aEx.createCriteria();
        criteria.andOpenIdEqualTo(withdraw.getOpenId());
        List<account> accounts = accountMapper.selectByExample(aEx);
        account account = accounts.get(0);
        if(new BigDecimal(account.getAccountMoneyBalance()).compareTo(new BigDecimal(withdraw.getNum()))!=-1){
            try{
                //生成的随机字符串
                String nonce_str = WXPayUtil.generateNonceStr();
                //获取客户端的ip地址
                //获取本机的ip地址
                InetAddress addr = null;
                try {
                    addr = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                String spbill_create_ip = addr.getHostAddress();
                //支付金额，需要转成字符串类型，否则后面的签名会失败
                //int  total_fee=1;
                String money = new BigDecimal(withdraw.getNum().toString()).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).toString();
                log.debug("提现金额"+money);
                //商品描述
                String body = "环保金提现";

                //提现用户类型
                String appid = "";
                if(withdraw.getUserType().equals("1")){
                    appid = "wx51d55df222d9901e";
                }else if(withdraw.getUserType().equals("0")){
                    appid = "wx1cf12dee9dbfe13c";
                }else if(withdraw.getUserType().equals("2")){
                    appid = "wx578244d5b6022c06";
                }

                //String out_trade_no = WXPayUtil.generateNonceStr();
                //统一下单接口参数
                HashMap<String, String> data = new HashMap<String, String>();
                data.put("mch_appid", appid);
                data.put("mchid", "1550181801");
                data.put("nonce_str", nonce_str);
                data.put("desc", body);
                data.put("partner_trade_no", withdraw.getNumber());
                data.put("openid", withdraw.getOpenId());
                data.put("check_name", "NO_CHECK");
                data.put("amount", money);
                data.put("spbill_create_ip", spbill_create_ip);

                String sign = WXPayUtil.generateSignature(data, "0B2DC615EA4F78BC4B216AEA1A6DA63B");//商户密码
                data.put("sign", sign);
                String xml = WXPayUtil.mapToXml(data);//将所有参数(map)转xml格式



                //企业付款
                String macPayUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

//            String xmlStr = HttpClientUtil.sendPost(macPayUrl, xml);
                String xmlStr = HttpClientUtil.posts(macPayUrl, xml);

                Map<String, String> reMap = WXPayUtil.xmlToMap(xmlStr);
                log.debug(reMap.toString());
                if (CollectionUtil.isNotEmpty(reMap) && "SUCCESS".equals(reMap.get("result_code"))) {
                    //成功需要进行的逻辑操作
                    log.debug("提现成功");
                    //修改骑手账户金额,修改提现记录状态

                    account.setAccountMoneyBalance(DoubleUtils.sub(account.getAccountMoneyBalance(),withdraw.getNum()));
                    log.debug("提现后账户金额");
                    log.debug(account.getAccountMoneyBalance().toString());
                    int i = accountMapper.updateByPrimaryKeySelective(account);
                    if(i==1){
                        //修改提现记录状态
                        withdraw.setState("已到账");
                        withdraw.setBillTime(new Date());
                        withdrawMapper.updateByPrimaryKeySelective(withdraw);

                        //添加消息记录
                        info info = new info();
                        info.setOpenid(withdraw.getOpenId());
                        info.setInfoTitle("提现成功提醒");
                        info.setInfoType("提现消息");
                        info.setInfoContent("您提现申请已经通过了，提现金额为："+withdraw.getNum()+",环保佣金已经到您的微信零钱了，请注意查收。");
                        info.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/money-icon.png");
                        info.setInfoTime(new Date());

                        infoMapper.insertSelective(info);

 //                       ------------------------------------------提现成功记录到WithdrawRechargeInfo中------------------------------------------
                        String isHorsemanOpenId = withdraw.getOpenId();
                        List<horseman> horsemen = horsemanMapper.selectHorsemanOpenId(isHorsemanOpenId);

                        if (horsemen.size()>0||!horsemen.isEmpty()){
                            List<order> orders = orderMapper.selectHorsemanStocksOrder(isHorsemanOpenId);
                            int orderId = 0;
                            if (orders.size()>0||!orders.isEmpty()){
                                orderId=orders.get(0).getId();
                            }
                            WithdrawRechargeInfo withdrawRechargeInfo =new WithdrawRechargeInfo();
                            withdrawRechargeInfo.setOrderId(orderId);
                            withdrawRechargeInfo.setWithdrawMoney(Long.parseLong(money)/100);
                            withdrawRechargeInfo.setWithdrawId(withdraw.getId());
                            withdrawRechargeInfo.setHorsemanAccount(horsemen.get(0).getOpenId());
                            withdrawRechargeInfo.setHorsemanName(horsemen.get(0).getHorsemanName());
                            withdrawRechargeInfo.setWithdrawTime(new Date());
                            withdrawRechargeInfoMapper.insertSelective(withdrawRechargeInfo);
                        }

//                        ------------------------------------------------------------------------------------


                        return true;
                    }else {
                        return false;
                    }


                }else {
                    //添加消息记录
                    info info = new info();
                    info.setOpenid(withdraw.getOpenId());
                    info.setInfoTitle("提现失败提醒");
                    info.setInfoType("提现消息");
                    info.setInfoContent("很抱歉，您提现金额为："+withdraw.getNum()+"的提现申请没有通过审核,请查看环保金是否有什么异常，如有疑问请拨打客服电话。");
                    info.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/money-icon.png");
                    info.setInfoTime(new Date());

                    infoMapper.insertSelective(info);

                    if (CollectionUtil.isNotEmpty(reMap)) {
                        //resMap.put("msg","提现失败:"+reMap.get("err_code") + ":" + reMap.get("err_code_des"));
                        log.debug("提现失败");
                        return false;
                    }
                    //resMap.put("code",0);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return true;
    }

    public Boolean lostEffect(Integer id){
        withdraw withdraw = new withdraw();
        withdraw.setId(id);
        withdraw.setState("已失效");
        int i = withdrawMapper.updateByPrimaryKeySelective(withdraw);
        //添加消息记录
        info info = new info();
        info.setOpenid(withdrawMapper.selectByPrimaryKey(id).getOpenId());
        info.setInfoTitle("提现失败提醒");
        info.setInfoType("提现消息");
        info.setInfoContent("很抱歉，您提现金额为："+withdrawMapper.selectByPrimaryKey(id).getNum()+"的提现申请没有通过审核,请查看环保金是否有什么异常，如有疑问请拨打客服电话。");
        info.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/money-icon.png");
        info.setInfoTime(new Date());

        infoMapper.insertSelective(info);
        if(i != 1){
            return false;
        }
        return true;
    }
}
